#include <iostream>
#include <vector>

using namespace std;

class Solution {
  public:
    bool search(vector<vector<char>> &maze, int x, int y) {
        int n = maze.size(), m = maze[0].size();

        if (x < 0 || x >= n || y < 0 || y >= m) return false;
        if (maze[x][y] == '#') return false;
        if (x == 0 || x == n - 1 || y == 0 || y == m - 1)
            return true;
        else {
            maze[x][y] = '#';
            bool b = (search(maze, x + 1, y) || search(maze, x - 1, y) || search(maze, x, y + 1) || search(maze, x, y - 1));
            maze[x][y] = '.';
            return b;
        }
    }
    bool Maze(vector<vector<char>> &maze) {
        int n = maze.size(), m = maze[0].size();
        int sx, sy;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (maze[i][j] == 'S') {
                    sx = i;
                    sy = j;
                }
        vector<vector<char>> exm(3 * n, vector<char>(3 * m, '#'));
        for (int i = 0; i < 3 * n; i++) {
            for (int j = 0; j < 3 * m; j++) {
                exm[i][j] = maze[i % 3][j % 3];
            }
        }

        return search(exm, sx + n, sy + m);
    }
};

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<char>> maze(n, vector<char>(m, '#'));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> maze[i][j];
        }
    }
    Solution sol;
    cout << sol.Maze(maze);
}